package cn.lena.executor;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author lena
 * @date 2021/6/22
 */
public class ExuecutorService {


	@Test
	public void create(){
		// 创建线程池
		ExecutorService threadPool = Executors.newFixedThreadPool(10);
		while(true) {
			threadPool.execute(new Runnable() { // 提交多个线程任务，并执行
				@Override
				public void run() {
					System.out.println(Thread.currentThread().getName() + " is running ..");
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}
	}

	@Test
	public void callable(){
		int taskSize=10;
		//创建一个线程池
		ExecutorService pool = Executors.newFixedThreadPool(taskSize);
		// 创建多个有返回值的任务
		List<Future> list = new ArrayList<Future>();
		for (int i = 0; i < taskSize; i++) {
			Callable c = new MyCallable(i + " ");
			// 执行任务并获取 Future 对象
			Future f = pool.submit(c);
			list.add(f);
		}
		// 关闭线程池
		pool.shutdown();
		// 获取所有并发任务的运行结果
		for (Future f : list) {
			// 从 Future 对象上获取任务的返回值，并输出到控制台
			try {
				System.out.println("res： " + f.get().toString());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		}
	}

}

class MyCallable implements Callable{

	private String s;

	MyCallable(String s){
		this.s=s;
	}

	@Override
	public Object call() throws Exception {
		System.out.println(s);
		return s;
	}
}
